<template>
  <section>
    <el-drawer ref="drawerRef"
               title="添加途径站"
               :before-close="handleClose"
               :visible.sync="drawer"
               :wrapper-closable="false"
               custom-class="demo-drawer">
      <div class="desc_sty">
        说明：<br />
        1、选择承运方自动带出站点信息；如无，填写的信息为临时站点；如需创建固定的站点信息，请先
        <el-button type="text"
                   @click="goStation">维护</el-button>。<br />
        2、选择了承运方，第一段拆分运单进入待调度列表，其他拆分运单将自动调度给对应的承运方，参照调度预览。<br />
        3、没有选择承运方，拆分运单进入待调度列表。
      </div>
      <div class="demo-drawer__content"
           style="margin-right: 20px">
        <el-form ref="ruleForm"
                 :model="form"
                 :rules="rules"
                 label-width="130px">
          <el-form-item prop="carrierId"
                        label="选择承运方">
            <el-select v-model="form.carrierId"
                       placeholder="请选择承运方"
                       :filterable="true"
                       clearable
                       style="width: 100%"
                       @change="handleChangeCarrier($event)">
              <el-option v-for="option in carrierOptions"
                         :key="option.carrierId"
                         :label="option.name"
                         :value="option.carrierId" />
            </el-select>
          </el-form-item>
          <el-form-item prop="stationName"
                        label="站点(收货方)">
            <el-select v-if="form.carrierId"
                       v-model="form.stationName"
                       filterable
                       allow-create
                       default-first-option
                       placeholder="请选择站点(收货方)"
                       style="width: 100%"
                       @change="stationHeadler">
              <el-option v-for="item in siteOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
            <consignee-info v-else
                            :value.sync="form.stationName"
                            :type="'consigneeName'"
                            :max="80"
                            :placeholder="`请输入站点(收货方)`"
                            :filters="filters"
                            v-bind="$attrs"
                            @input="selectConsignee" />
          </el-form-item>
          <el-form-item prop="address"
                        label="中转地址">
            <!-- <area-select v-model="form.address"
                         align="center"
                         type="code"
                         :area-values="[
                  form.address.provinceCode,
                  form.address.cityCode,
                  form.address.districtCode
                ]"
                         @input="selectFromArea" /> -->
            <area-cascader v-model="form.address"
                           :props="props" />
          </el-form-item>
          <template v-for="(ele, i) in associate">
            <el-form-item :key="i"
                          :prop="ele.prop"
                          :label="ele.label">
              <consignee-info :value.sync="form[ele.prop]"
                              :type="ele.argName"
                              :max="ele.max"
                              :placeholder="`请输入${ele.label}`"
                              :filters="filters"
                              v-bind="$attrs"
                              @input="selectConsignee" />
            </el-form-item>
          </template>
          <el-form-item prop="toTime"
                        label="要求到站时间">
            <el-date-picker v-model="form.toTime"
                            align="left"
                            type="datetime"
                            placeholder="请选择要求到站时间"
                            style="width: 100%"
                            :picker-options="pickerOptions"
                            format="yyyy-MM-dd HH:mm"
                            :default-time="'00:00:00'"
                            popper-class="no-atTheMoment" />
          </el-form-item>
        </el-form>
        <div class="drawer_footer">
          <el-button type="primary"
                     plain
                     @click="handleClose">取 消</el-button>
          <el-button type="primary"
                     :loading="loading"
                     @click="handleSubmit">{{
            loading ? "提交中 ..." : "确 定"
          }}</el-button>
        </div>
      </div>
    </el-drawer>
  </section>
</template>

<script>
import { station } from "@/api/index";
import { returnCompareTime, returnHourMinute } from "@/libs/util.js";
import AreaCascader from "@basic/area/AreaCascader.vue";
import ConsigneeInfo from "@components/advance/orderAddress/ConsigneeInfo.vue";
export default {
  name: "StationDrawer",
  components: { AreaCascader, ConsigneeInfo },
  props: {
    drawer: {
      type: Boolean,
      default: () => false
    },
    carrierOptions: {
      type: Array,
      default: () => []
    },
    toTime: {
      type: String,
      default: () => null
    },
    fromTime: {
      type: String,
      default: () => null
    },
    selectableRange: {
      type: String,
      default: () => `00:00:00 - 23:59:59`
    }
  },
  data () {
    return {
      stationList: [],
      props: {
        label: 'name',
        value: 'areaCode',
        checkStrictly: true
      },
      form: {
        carrierId: null,
        carrierName: null,
        stationName: null,
        address: {
          provinceCode: null,
          cityCode: null,
          districtCode: null
        },
        stationAddres: null,
        stationAreaName: null,
        contactName: null,
        contactMobile: null,
        toTime: null
      },
      rules: {
        stationName: [{ required: true, message: "请输入站点(收货方)", trigger: "blur" }],
        address: [{ required: true, message: "请选择中转地址", trigger: "change" }],
        stationAddres: [{ required: true, message: "请输入中转详细地址", trigger: "blur" }],
        contactName: [{ required: true, message: "请输入联系人", trigger: "blur" }],
        contactMobile: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
        toTime: [{ required: true, message: "请选择要求到站时间", trigger: "change" }]
      },
      siteOptions: [],
      pickerOptions: {
        // 时间选择限制 发货时间
        disabledDate: (time) => {
          return (
            time.getTime() >= new Date(this.toTime).getTime() ||
            time.getTime() <=
            new Date(
              new Date(this.fromTime).setDate(
                new Date(this.fromTime).getDate() - 1
              )
            ).getTime()
          );
        },
        selectableRange: this.selectableRange
      },
      loading: false
    };
  },
  computed: {
    associate () {
      return [
        { label: '详细地址', prop: 'stationAddres', argName: 'address', max: 100 },
        { label: '联系人', prop: 'contactName', argName: 'contactName', max: 20 },
        { label: '联系电话', prop: 'contactMobile', argName: 'contactMobile', max: 50 }
      ]
    },
    filters () {
      return {
        sort: { name: "divideHots", asc: false }
      }
    }
  },
  watch: {
    form: {
      handler (val) {
        if (val.toTime) {
          let fromflag = returnCompareTime(
            new Date(this.$moment(val.toTime).format("YYYY-MM-DD HH:mm:ss")),
            new Date(this.fromTime)
          );
          let toflag = returnCompareTime(
            new Date(this.$moment(val.toTime).format("YYYY-MM-DD HH:mm:ss")),
            new Date(this.toTime)
          );
          // 选中的时间早于发货时间,晚于到货时间, val.toTime = 发货时间分钟数+1
          if (!fromflag || toflag) {
            let fTime = this.$moment(this.fromTime).format("YYYY-MM-DD HH:mm:ss");
            let tTime = returnHourMinute(
              fTime.substring(10, 13),
              fTime.substring(14, 16),
              true
            );
            let tTimeValue = this.$moment(this.fromTime).format(
              `YYYY-MM-DD ${tTime}`
            );
            return val.toTime = tTimeValue;
          }
          let formDays = this.$moment(this.fromTime)
            .format("YYYY-MM-DD HH:mm")
            .substring(0, 10);
          let toDays = this.$moment(this.toTime)
            .format("YYYY-MM-DD HH:mm")
            .substring(0, 10);
          let days = this.$moment(val.toTime)
            .format("YYYY-MM-DD HH:mm")
            .substring(0, 10);
          if (formDays === toDays) {
            this.pickerOptions.selectableRange = this.selectableRange;
          } else {
            if (days === formDays) {
              this.pickerOptions.selectableRange = `${this.selectableRange.substring(
                0,
                8
              )} - 23:59:59`;
              if (!fromflag) {
                val.toTime = this.$moment(val.toTime).format(
                  `YYYY-MM-DD ${this.selectableRange.substring(0, 5)}`
                );
              }
            } else if (days === toDays) {
              this.pickerOptions.selectableRange = `00:00:00 - ${this.selectableRange.substring(
                11,
                20
              )}`;
              if (toflag) {
                val.toTime = this.$moment(val.toTime).format(
                  `YYYY-MM-DD${this.selectableRange.substring(11, 17)}`
                );
              }
            } else {
              this.pickerOptions.selectableRange = `00:00:00 - 23:59:59`;
            }
          }
        }
      },
      deep: true
    }
  },
  created () {
    if (this.selectableRange) {
      let fristHour = Number(this.selectableRange.substring(0, 2));
      let lastHour = Number(this.selectableRange.substring(10, 13));
      if (fristHour > lastHour) {
        this.pickerOptions.selectableRange = `${this.selectableRange.substring(
          0,
          8
        )} - 23:59:59`;
      } else if (fristHour === lastHour) {
        let fristMinute = Number(this.selectableRange.substring(3, 5));
        let lastMinute = Number(this.selectableRange.substring(14, 16));
        if (fristMinute > lastMinute) {
          this.pickerOptions.selectableRange = `00:00:00 - ${this.selectableRange.substring(
            11,
            19
          )}`;
        }
      }
    }
  },
  methods: {
    // 联想收货信息
    selectConsignee (val) {
      let { address: addressAres } = this.form;
      let { address, consigneeName, cityCode, city, districtCode, district, provinceCode, province, ...params } = val;
      let area = { cityCode: Number(cityCode), city, districtCode: Number(districtCode), district, provinceCode: Number(provinceCode), province }

      // address = Object.assign(address, area);
      this.form = Object.assign(this.form, {
        ...params,
        addressAres: Object.assign(addressAres, area),
        stationAddres: address,
        stationName: consigneeName,
        address: area
      });
      return this.form;
    },
    // 选择承运商
    handleChangeCarrier (val) {
      if (val) {
        let obj = this.carrierOptions.find(i => i.carrierId === val);
        this.form.carrierName = obj?.name;
        this.getSataionList({ page: 1, size: 9999, carrierId: val });
      } else {
        this.form.carrierName = null;
        this.form.carrierId = null;
      }
    },
    // 站点下拉
    async getSataionList (params) {
      let { code, data } = await station.search(params);
      if (code === 0 && data.records && data.records.length) {
        this.stationList = data.records
        this.siteOptions = data.records.map(item => {
          return { label: item.name, value: item.name }
        })
        this.stationAssignment({ records: data.records, need: true })
        this.$refs.ruleForm.validate((valid) => {
          console.log("valid", valid)
        });
      } else {
        this.siteOptions = []
        this.form.stationId = ''
        this.form.stationName = ''
        this.form.address = {}
        // this.form.stationAreaName = ''
        this.form.stationAddres = ''
        this.form.contactName = ''
        this.form.contactMobile = ''
      }
    },
    stationHeadler (value) {
      const record = this.stationList.filter(item => item?.name === value)
      this.stationAssignment({ records: record, need: false })
    },
    // 地区
    // selectFromArea (val) {
    //   this.form.address = { ...val }
    // },
    handleSubmit () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const params = {
            contact: {
              contactMobile: this.form?.contactMobile,
              contactName: this.form?.contactName
            },
            address: {
              ...this.form?.address,
              address: this.form?.stationAddres,
              // province: this.form?.address.province,
              // city: this.form?.address.city,
              // district: this.form?.address.district,
              // provinceCode: this.form?.address.provinceCode,
              // cityCode: this.form?.address.cityCode,
              // districtCode: this.form?.address.districtCode
            },
            carrierId: this.form.carrierId || null,
            carrierName: this.form.carrierName,
            stationName: this.form.stationName,
            stationAreaName: `${this.form?.address.province} ${this.form?.address.city} ${this.form?.address.district} ${this.form?.stationAddres}`
          }
          this.$emit("changeListData", {
            ...params,
            toTime: this.$moment(this.form.toTime).format("YYYY-MM-DD HH:mm")
          });
          this.handleClose();
        }
      });
    },
    handleClose () {
      this.$emit("update:drawer", false);
    },
    stationAssignment ({ records, need }) {
      if (records.length) {
        const record = records[0];
        const form = this.form;
        form.contact = {
          contactMobile: record?.contactMobile,
          contactName: record?.contactName
        }
        form.carrierName = record.carrierName;
        form.carrierId = record.carrierId;
        // form.stationId = record.stationId;
        if (need) {
          form.stationName = record.name;
        }

        form.address = {
          address: form.stationAddres,
          province: record?.province,
          city: record?.city,
          district: record?.district,
          provinceCode: record.provinceCode,
          cityCode: record.cityCode,
          districtCode: record.districtCode
        };
        form.stationAddres = record.address;
        form.contactName = record.contactName;
        form.contactMobile = record.contactMobile;
      }

    },
    goStation () {
      this.$router.push({
        path: `/board/eyJ0eXBlIjoiZm9ybSIsIm1lbnVJZCI6IjU2IiwicmVzb3VyY2VJZCI6MTEyfQ`,
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.drawer_footer {
  position: absolute;
  top: 95%;
  left: 40%;
}
.no-atTheMoment
  .el-picker-panel__footer
  .el-button--text.el-picker-panel__link-btn {
  display: none !important;
}
.ml8 {
  margin-left: 8px;
}
/deep/ .el-drawer {
  width: 34% !important;
}
/deep/ .el-drawer__header {
  align-items: center;
  color: var(--prev-color-text-primary);
  font-size: 16px;
  font-weight: bold;
  display: flex;
  padding: 18px;
  margin-bottom: 0px;
}
.desc_sty {
  color: var(--prev-color-text-darkgrey);
  padding: 0px 20px 20px;
  line-height: 24px;
  font-size: 12px;
}
</style>
